package com.woniuxy.yoga.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.yoga.business.client.CourseClient;
import com.woniuxy.yoga.business.client.OrderClient;
import com.woniuxy.yoga.business.dao.mapper.BusinessStoreMapper;
import com.woniuxy.yoga.business.dao.model.BusinessStore;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.yoga.business.dao.mapper.BusinessStoreMapper;
import com.woniuxy.yoga.business.dao.model.BusinessStore;
import com.woniuxy.yoga.business.dao.model.StoreCount;
import com.woniuxy.yoga.business.dao.mapper.StoreCountMapper;
import com.woniuxy.yoga.business.model.dto.orderinfo.DataDto;
import com.woniuxy.yoga.business.model.dto.storecount.StoreCountSelectDTO;
import com.woniuxy.yoga.business.model.exception.BusinessException;
import com.woniuxy.yoga.business.model.form.course.AmountAloneCourseDurationForm;
import com.woniuxy.yoga.business.model.form.course.AmountOrdinaryCourseDurationForm;
import com.woniuxy.yoga.business.model.form.course.AmountTeamCourseDurationForm;
import com.woniuxy.yoga.business.model.form.course.CountMonthCourseTimeForm;
import com.woniuxy.yoga.business.model.form.orderinfo.GetDataForm;
import com.woniuxy.yoga.business.model.dto.storecount.StaticDataDto;
import com.woniuxy.yoga.business.model.exception.BusinessException;
import com.woniuxy.yoga.business.model.exception.BusinessExceptionCode;
import com.woniuxy.yoga.business.model.form.storecount.StoreCountSelForm;
import com.woniuxy.yoga.business.service.StoreCountService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.yoga.commons.core.model.PageInfo;
import com.woniuxy.yoga.commons.core.model.Result;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.management.Query;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 商家统计表 服务实现类
 * </p>
 *
 * @author 韦用文,刘存益,郎腾霄
 * @since 2023年11月28日
 */
@Service
public class StoreCountServiceImpl extends ServiceImpl<StoreCountMapper, StoreCount> implements StoreCountService {

    @Autowired
    private OrderClient orderClient;
    @Autowired
    private StoreCountMapper storeCountMapper;
    @Autowired
    private BusinessStoreMapper businessStoreMapper;
    @Autowired
    private StoreCountService storeCountService;
    @Autowired
    private CourseClient courseClient;



    /**
     * 每月1号1点定时统计月营业额
     */
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public void timingStoreCount() {
        Calendar calendar = Calendar.getInstance();
        // 获取当前时间
        calendar.setTimeInMillis(System.currentTimeMillis());
        // 将时间设置为上一个月
        calendar.add(Calendar.MONTH, 0);
        // 获取上一个月的开始时间
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        long startTime = calendar.getTimeInMillis();
        // 获取上一个月的结束时间
        calendar.add(Calendar.MONTH, 1);
        calendar.add(Calendar.SECOND, -1);
        long endTime = calendar.getTimeInMillis();
        String start = DateUtil.formatDateTime(new Date(startTime));
        String end = DateUtil.formatDateTime(new Date(endTime));
        //查询所有的门店
        List<BusinessStore> businessStores = businessStoreMapper.selectList(new LambdaQueryWrapper<>());
        ArrayList<StoreCount> storeCounts = new ArrayList<>();
        if (businessStores!=null&&businessStores.size()!=0) {
            for (BusinessStore businessStore : businessStores) {
                //开始统计流水和订单量
                GetDataForm getDataForm = new GetDataForm();
                getDataForm.setEndTime(end);
                getDataForm.setStartTime(start);
                getDataForm.setStoreId(businessStore.getStoreId());
                //调用查询月成交量的接口 成交量 营业额
                Result<DataDto> orderResult = orderClient.getDataByTime(getDataForm);
                if (orderResult.getCode()==500)throw new BusinessException(500,"系统错误");
                if (orderResult.getCode()!=200)throw new BusinessException(orderResult.getCode(),orderResult.getMessage());
                //开始统计月课时
                CountMonthCourseTimeForm form = new CountMonthCourseTimeForm();
                form.setStoreId(businessStore.getStoreId());
                form.setEndTime(end);
                form.setStartTime(start);
                AmountAloneCourseDurationForm aloneForm = BeanUtil.toBean(form, AmountAloneCourseDurationForm.class);
                AmountOrdinaryCourseDurationForm ordinaryForm = BeanUtil.toBean(form, AmountOrdinaryCourseDurationForm.class);
                AmountTeamCourseDurationForm teamForm = BeanUtil.toBean(form, AmountTeamCourseDurationForm.class);
                //调用接口查询私教课总课时
                Result<Integer> courseReult = courseClient.amountAloneCourseDuration(aloneForm);
                if (courseReult.getCode()==500)throw new BusinessException(500,"系统错误");
                if (courseReult.getCode()!=200)throw new BusinessException(courseReult.getCode(),courseReult.getMessage());
                //调用接口查询普通课总课时
                Result<Integer> ordinaryCourseReult = courseClient.amountOrdinaryCourseDuration(ordinaryForm);
                if (ordinaryCourseReult.getCode()==500)throw new BusinessException(500,"系统错误");
                if (ordinaryCourseReult.getCode()!=200)throw new BusinessException(ordinaryCourseReult.getCode(),ordinaryCourseReult.getMessage());
                //调用接口查询团课总课时
                Result<Integer> teamCourseReult = courseClient.amountTeamCourseDuration(teamForm);
                if (teamCourseReult.getCode()==500)throw new BusinessException(500,"系统错误");
                if (teamCourseReult.getCode()!=200)throw new BusinessException(teamCourseReult.getCode(),teamCourseReult.getMessage());
                //计算月总课时
                Integer courseCount = courseReult.getData()+ordinaryCourseReult.getData()+teamCourseReult.getData();
                StoreCount storeCount = new StoreCount();
                // 提取年份
                String yearString = start.substring(0, 4);
                int year = Integer.parseInt(yearString);
                // 提取月份
                String monthString = start.substring(5, 7);
                int month = Integer.parseInt(monthString);
                storeCount.setStoreId(businessStore.getStoreId());
                storeCount.setYear(year);
                storeCount.setMonth(month);
                storeCount.setMonthOrder(orderResult.getData().getOrder());
                storeCount.setMonthTurnover(orderResult.getData().getTurnover().divide(new BigDecimal(10000)));
                storeCount.setMonthCourse(courseCount);
                storeCount.setCountTime(DateUtil.format(new Date(System.currentTimeMillis()), "yyyy-MM-dd HH:mm:ss"));
                storeCounts.add(storeCount);
            }
            storeCountService.saveBatch(storeCounts);
        }
    }

    /**
     * 根据条件分页查询商店统计表
     * @param form
     * @return
     */
    @Override
    public PageInfo selStoreStatis(StoreCountSelForm form) {
        //创建分页查询对象
        Page<StoreCount> page = new Page<>(form.getCurrent() == null ? 1 : form.getCurrent(),
                form.getSize() == null ? 10 : form.getSize());
        //查询条件
        LambdaQueryWrapper<StoreCount> wrapper = new LambdaQueryWrapper<>();
        //当存在门店ID条件时
        if (form.getStoreId()!=null&&!form.getStoreId().equals("")){
            wrapper.eq(StoreCount::getStoreId,form.getStoreId());
        }
        //当存在查询月份时
        if (form.getMonth()!=null&&!form.getMonth().equals("")){
            wrapper.eq(StoreCount::getMonth,form.getMonth());
        }
        //当存在查询年份时
        if (form.getYear()!=null&&!form.getMonth().equals("")){
            wrapper.eq(StoreCount::getYear,form.getYear());
        }
        storeCountMapper.selectPage(page, wrapper);
        PageInfo pageInfo = BeanUtil.toBean(page, PageInfo.class);
        pageInfo.setRecords(BeanUtil.copyToList(page.getRecords(), StoreCountSelectDTO.class));
        pageInfo.setPages(page.getPages());
        return pageInfo;
    }

    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        // 获取当前时间
        calendar.setTimeInMillis(System.currentTimeMillis());
        // 将时间设置为上一个月
        calendar.add(Calendar.MONTH, 0);
        // 获取上一个月的开始时间
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        long startTime = calendar.getTimeInMillis();
        // 获取上一个月的结束时间
        calendar.add(Calendar.MONTH, 1);
        calendar.add(Calendar.SECOND, -1);
        long endTime = calendar.getTimeInMillis();
        String start = DateUtil.formatDateTime(new Date(startTime));
        String end = DateUtil.formatDateTime(new Date(endTime));
        System.out.println(start);
        System.out.println(end);
        System.out.println(new BigDecimal(699999).divide(new BigDecimal(10000)));
    }

    /**
     * 查询统计图数据
     * @param accountId 账户id
     * @return StaticDataDto
     */
    @Override
    public StaticDataDto monthStaticData(Integer accountId) {
        //查询门店id
        QueryWrapper<BusinessStore> wrapper = new QueryWrapper<>();
        wrapper.eq("account_id",accountId);
        BusinessStore businessStore = businessStoreMapper.selectOne(wrapper);
        if (businessStore==null) throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_ACCOUNT_NOTEXITS);
        QueryWrapper<StoreCount> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id",businessStore.getStoreId());
        //获取当前年份信息
        String year = String.valueOf(LocalDate.now().getYear());
        queryWrapper.eq("year",year);
        //创建返回对象
        StaticDataDto staticDataDto = new StaticDataDto();
        //创建月流水集合
        List<String> monthMoney = new ArrayList<>();
        //创建月订单量集合
        List<String> monthOrder = new ArrayList<>();
        //创建月课时集合
        List<String> monthCourseHour = new ArrayList<>();
        //取出今年数据放入集合
        List<StoreCount> storeCounts = storeCountMapper.selectList(queryWrapper);
        //如果为空设为0，防止前端无法获取
        if (storeCounts.size()==0) {
            //获取当前日期月份
            Calendar calendar = Calendar.getInstance();
            int month = calendar.get(Calendar.MONTH)+1;
            System.out.println(month);
            //当前月份为多少则循环多少次数据
            for (int i = 0; i < month; i++) {
                monthMoney.add("0");
                monthOrder.add("0");
                monthCourseHour.add("0");
            }
            staticDataDto.setMonthMoney(monthMoney);
            staticDataDto.setMonthOrder(monthOrder);
            staticDataDto.setMonthCourseHour(monthCourseHour);
            return staticDataDto;
        }
        //取出每一个月的数据存入集合
        //获取当前日期月份
        Calendar calendar = Calendar.getInstance();
        int month = calendar.get(Calendar.MONTH)+1;
        for (int i=1;i<=month;i++){
            if (i==storeCounts.get(i-1).getMonth()){
                monthMoney.add(storeCounts.get(i-1).getMonthTurnover()==null?"0":storeCounts.get(i-1).getMonthTurnover()+"");
                monthOrder.add(storeCounts.get(i-1).getMonthOrder()==null?"0":storeCounts.get(i-1).getMonthOrder()+"");
                monthCourseHour.add(storeCounts.get(i-1).getMonthCourse()==null?"0":storeCounts.get(i-1).getMonthCourse()+"");
            }
        }
        staticDataDto.setMonthMoney(monthMoney);
        staticDataDto.setMonthOrder(monthOrder);
        staticDataDto.setMonthCourseHour(monthCourseHour);
        return staticDataDto;
    }
}
